import { loginService, registerService } from '@/services/User';
import { reactive, Ref, toRefs } from 'vue';
import { Storage } from '@/libs/utils';

//前端提交的表单数据校验用户名或者密码长度的方法
function checkUserInfo(field: Ref, num: number): Boolean {
  return field.value.length >= num;
}

export function useLogin() {
  const state = reactive({
    username: '',
    password: ''
  });
  const submitUserInfo = async () => {
    return await loginService({
      username: state.username,
      password: state.password
    });
  };
  return {
    ...toRefs(state), //解包为ref引用
    checkUserInfo,
    submitUserInfo
  };
}

export function useStorage() {
  const setUserStorage = (accessToken: string, level: string) => {
    Storage.set('access_token', accessToken);
    Storage.set('user_level', level);
  };
  const removeUserStorage = () => {
    Storage.remove('access_token');
    Storage.remove('user_level');
  };
  return {
    setUserStorage,
    removeUserStorage
  };
}

export function useRegister() {
  const state = reactive({
    username: '',
    password: '',
    rePassword: ''
  });
  const submitUserInfo = async () => {
    return await registerService({
      username: state.username,
      password: state.password
    });
  };
  const comparePassword = (): boolean => {
    return state.password === state.rePassword;
  };
  return {
    ...toRefs(state),
    submitUserInfo,
    checkUserInfo,
    comparePassword
  };
}
